package sg.edu.nus.iss.billing;

import java.util.Iterator;
import java.util.List;

import javax.swing.JComponent;

import sg.edu.nus.iss.billing.dao.BaseDAO;
import sg.edu.nus.iss.billing.dao.DaoFactory;
import sg.edu.nus.iss.billing.exceptions.ControllerException;
import sg.edu.nus.iss.billing.gui.BillingWindow;
import sg.edu.nus.iss.billing.gui.LoginWindow;
import sg.edu.nus.iss.billing.model.user.User;
import sg.edu.nus.iss.billing.model.user.User.SystemAcctStatus;

/**
 * @author Yeo Hee Ling, Ananda, BeeHong
 *
 */
public class BillingApplication {
	
	// Declaration of Global Variables.
	private static User userSession;
	private LoginWindow loginWindow;
	private BillingWindow billingWindow;
	
	// Class Constructor.
	public BillingApplication() {
		this.loginWindow = new LoginWindow(this);
	}
	
	public static User getUserSession() {
		return userSession;
	}

	public void setUserSession(User userSession) {
		BillingApplication.userSession = userSession;
	}

	public boolean doLogin(String username, String password) throws ControllerException {
		boolean validUser = false;
		boolean isSystemAcctSusp = false;
		
		try {
			BaseDAO<User> dao = DaoFactory.getUserDAO(BillingConstants.DATASOURCE_USER);
			
			List<User> users = dao.getElementListByAttribute("userName", username);
			if(users != null && users.size() > 0) {
				Iterator<User> iter = users.iterator();
				while(iter.hasNext()) {
					User user = iter.next();
					if(username.equals(user.getUserName())) {
						if(password.equals(user.getPassword())) {
							validUser = true;
							userSession = user;
							
							if(SystemAcctStatus.Suspended.toString().equals(user.getSystemAcctStatus().toString()))
								isSystemAcctSusp = true;
						}
					}
				}
			}
		}
		catch(Exception ex) {
			ex.printStackTrace();
			throw new ControllerException("Unable to login to One# Billing Application due to technical error. \nPlease contact your local administrator.");
		}
		
		if(isSystemAcctSusp) {
			throw new ControllerException("Login Failed. Your System Account has been suspended. \nPlease contact your administrator.");
		}
		return validUser;
	}
	
	public void displayMainMenu() {
		loginWindow.setVisible(false);
		billingWindow = new BillingWindow(this);
	}

	public void displayLoginPage() {
		billingWindow.dispose();
		loginWindow.setVisible(true);
	}
	
	public void displayPage(JComponent component){
		billingWindow.switchPage(component);
	}
	
	public void shutdown() {
		System.exit(0);
	}
	
	public static void main (String args[]) {
		try {
			new BillingApplication();
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}